package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.WxConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.wx.HttpClientSslUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.BdmGoodDto;
import com.ruoyi.system.domain.dto.IntegralGoodDto;
import com.ruoyi.system.domain.dto.PointExchangeRecordDto;
import com.ruoyi.system.domain.dto.UserPraiseDto;
import com.ruoyi.system.domain.dto.importDto.BdmImportGoodDto;
import com.ruoyi.system.domain.vo.BamCloudInventoryVo;
import com.ruoyi.system.domain.vo.BdmCloudInventoryItemVo;
import com.ruoyi.system.domain.vo.BdmCloudInventoryItemVoList;
import com.ruoyi.system.domain.vo.PointExchangeRecord;
import com.ruoyi.system.domain.vo.applet.AppletBdmGoodVo;
import com.ruoyi.system.domain.vo.applet.AppletBdmUserIntegralGoodVo;
import com.ruoyi.system.domain.vo.applet.CommodityDetailsVo;
import com.ruoyi.system.domain.vo.applet.ProductReviewsVo;
import com.ruoyi.system.enums.BdmGoodEnum;
import com.ruoyi.system.mapper.BdmGoodMapper;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 代理商商品Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-07
 */
@Slf4j
@Service
public class BdmGoodServiceImpl extends ServiceImpl<BdmGoodMapper, BdmGood> implements IBdmGoodService {
    @Autowired
    private BdmGoodMapper bdmGoodMapper;

    @Autowired
    private IBdmUserPraiseService bdmUserPraiseService;

    @Autowired
    private IBdmUserCollectService bdmUserCollectService;

    @Autowired
    private IBdmMemberRuleService bdmMemberRuleService;

    @Autowired
    private IBdmUserService bdmUserService;

    //获取事务
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Autowired
    private IBdmGoodclassifyService iBdmGoodclassifyService;

    @Autowired
    private IBdmShippingCostService bdmShippingCostService;

    @Autowired
    private IBdmOrderItemService bdmOrderItemService;

    @Autowired
    private IBdmOrderService bdmOrderService;

    /**
     * 查询代理商商品
     *
     * @param id 代理商商品主键
     * @return 代理商商品
     */
    @Override
    public BdmGood selectbdmGoodById(Long id) {
        return bdmGoodMapper.selectbdmGoodById(id);
    }

    /**
     * 查询代理商商品列表
     *
     * @param bdmGood 代理商商品
     * @return 代理商商品
     */
    @Override
    public List<BdmGood> selectbdmGoodList(BdmGood bdmGood) {
        return bdmGoodMapper.selectbdmGoodList(bdmGood);
    }

    /**
     * 首页搜索
     *
     * @param search
     * @return
     */
    @Override
    public List<BdmGood> selectHomeContents(String search) {
        return bdmGoodMapper.selectHomeContents(search);
    }

    /**
     * 查询推荐商品列表
     *
     * @param bdmGood 代理商商品
     * @return 代理商商品
     */
    @Override
    public List<AppletBdmGoodVo> selectHomeReferralsGoodList(BdmGood bdmGood) {
        bdmGood.setIsTop("1");
        bdmGood.setDelFlag("1");

        Long sysUid = SecurityUtils.getUserId();
        // 查询当前角色等级
        BdmMemberRule bdmMemberRule = new BdmMemberRule();
        bdmMemberRule.setSysUserid(sysUid);
        List<BdmMemberRule> memberRuleList = bdmMemberRuleService.selectBdmMemberRuleList(bdmMemberRule);
        if (StringUtils.isNotEmpty(memberRuleList)) {
            // 是会员
            BdmMemberRule memberRule = memberRuleList.get(0);
            String level = String.valueOf(StringUtils.isNotNull(memberRule.getMemberAgencyLevel()) ? memberRule.getMemberAgencyLevel() : memberRule.getMemberLevel());
            switch (level) {
                case "1": // vip
                    bdmGood.setMemberBuyingRights("2");
                    break;
                case "2": // svip
                    bdmGood.setMemberBuyingRights("3");
                    break;
                case "3": // 共享店主
                    bdmGood.setMemberBuyingRights("4");
                    break;
                case "4": // 联创
                    bdmGood.setMemberBuyingRights("5");
                    break;
                case "5": // 区域运营中心
                    bdmGood.setMemberBuyingRights("6");
                    break;
                case "6": // 总裁
                    bdmGood.setMemberBuyingRights("7");
                    break;
                default:
                    bdmGood.setMemberBuyingRights("1"); // 普通
                    break;
            }
        } else {
            // 普通用户
            bdmGood.setMemberBuyingRights("1"); // 普通
        }

        Random random = new Random();
        List<BdmGood> list = Optional.ofNullable(bdmGoodMapper.selectbdmGoodList(bdmGood))
                .orElse(Collections.emptyList())
                .stream()
                .sorted(Comparator.comparingInt(o -> random.nextInt()))
                .limit(10)
                .collect(Collectors.toList());
        List<AppletBdmGoodVo> voList = new ArrayList<>();
        list.forEach(good -> {
            AppletBdmGoodVo vo = BeanUtil.copyProperties(good, AppletBdmGoodVo.class);
            vo.setDiscountPrice(BigDecimal.ZERO);
            UserPraiseDto dto = new UserPraiseDto();
            dto.setSysUid(sysUid);
            dto.setItemId(good.getId());
            vo.setGoodSpecs(good.getGoodSpecs());
            vo.setIsLike(bdmUserPraiseService.isLike(dto));
            vo.setDiscountPrice(goodPrice(good, bdmGood.getMemberBuyingRights())); // 会员折扣价
            vo.setIsCollect(bdmUserCollectService.isCollect(dto));
            voList.add(vo);
        });
        return voList;
    }

    /**
     * 商品价格
     *
     * @return
     */
    public BigDecimal goodPrice(BdmGood bdmGood, String level) {
        BigDecimal bigDecimal;
        switch (level) {
            case "2": // vip
                bigDecimal = bdmGood.getVipPrice();
                break;
            case "3": // svip
                bigDecimal = bdmGood.getSvipPrice();
                break;
            case "4": // 共享店主
                bigDecimal = bdmGood.getSharePrice();
                break;
            case "5": // 联创
                bigDecimal = bdmGood.getJoinPrice();
                break;
            case "6": // 区域运营中心
                bigDecimal = bdmGood.getOperationsPrice();
                break;
            case "7": // 总裁
                bigDecimal = bdmGood.getPresidentPrice();
                break;
            default: // 售价
                bigDecimal = bdmGood.getRetailPrice();
                break;
        }
        return bigDecimal;
    }


    /**
     * 新增代理商商品
     *
     * @param bdmGood 代理商商品
     * @return 结果
     */
    @Override
    public int insertbdmGood(BdmGood bdmGood) {
        bdmGood.setCreateTime(DateUtils.getNowDate());
        return bdmGoodMapper.insertbdmGood(bdmGood);
    }

    /**
     * 修改代理商商品
     *
     * @param bdmGood 代理商商品
     * @return 结果
     */
    @Override
    public int updatebdmGood(BdmGood bdmGood) {
        bdmGood.setUpdateTime(DateUtils.getNowDate());
        return bdmGoodMapper.updatebdmGood(bdmGood);
    }

    /**
     * 批量删除代理商商品
     *
     * @param ids 需要删除的代理商商品主键
     * @return 结果
     */
    @Override
    public int deletebdmGoodByIds(Long[] ids) {
        return bdmGoodMapper.deletebdmGoodByIds(ids);
    }

    /**
     * 删除代理商商品信息
     *
     * @param id 代理商商品主键
     * @return 结果
     */
    @Override
    public int deletebdmGoodById(Long id) {
        return bdmGoodMapper.deletebdmGoodById(id);
    }

    /**
     * 查询 小程序 商品列表
     *
     * @return
     */
    @Override
    public List<AppletBdmGoodVo> listGoodVo(BdmGoodDto bdmGoodDto) {
        try {
            bdmGoodDto.setUserId(SecurityUtils.getUserId());
        } catch (Exception e) {
            bdmGoodDto.setUserId(1l);
        }

        return bdmGoodMapper.listGoodVo(bdmGoodDto);
    }

    /**
     * 根据商品 id查询 小程序 商品
     *
     * @param goodId
     * @return
     */
    @Override
    public AppletBdmGoodVo goodVo(Long goodId) {
        long userId = 1;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            userId = 1;
        }
        // userId =SecurityUtils.getUserId();
        AppletBdmGoodVo appletBdmGoodVo = bdmGoodMapper.goodVo(goodId, userId);
        Integer inventoryVersion = appletBdmGoodVo.getInventoryVersion();
        if (inventoryVersion != 0) {
            // 限购数量
            ArrayList<Long> orderStatus = new ArrayList<>();
            orderStatus.add(5L);
            orderStatus.add(6L);
            List<BdmOrder> orderList = bdmOrderService.lambdaQuery().eq(BdmOrder::getUserId, userId).notIn(BdmOrder::getOrderStatus, orderStatus).list();
            if (!CollectionUtils.isEmpty(orderList)) {
                List<String> orderIds = orderList.stream().map(BdmOrder::getId).collect(Collectors.toList());
                int productCount = bdmOrderItemService.lambdaQuery().in(BdmOrderItem::getOrderId, orderIds)
                        .list()
                        .stream()
                        .filter(item -> goodId.equals(Long.parseLong(item.getSupplierGoodId()))).mapToInt(item -> Integer.parseInt(item.getGoodCount())).sum();
                inventoryVersion = inventoryVersion - productCount;
                if (inventoryVersion == 0) {
                    inventoryVersion = -1;
                }
                appletBdmGoodVo.setInventoryVersion(inventoryVersion);
            }
        }
        return appletBdmGoodVo;
    }

    public void verifyNumber(Long inventoryVersion, Long userId, Long productId, int number) {
        // 若限购数量为 0，表示不限制，直接返回
        if (inventoryVersion == 0) {

        } else {
            // 限购数量
            ArrayList<Long> orderStatus = new ArrayList<>();
            orderStatus.add(5L);
            orderStatus.add(6L);
            List<BdmOrder> orderList = bdmOrderService.lambdaQuery().eq(BdmOrder::getUserId, userId).notIn(BdmOrder::getOrderStatus, orderStatus).list();
            if (!CollectionUtils.isEmpty(orderList)) {
                List<String> orderIds = orderList.stream().map(BdmOrder::getId).collect(Collectors.toList());
                int productCount = bdmOrderItemService.lambdaQuery().in(BdmOrderItem::getOrderId, orderIds)
                        .list()
                        .stream()
                        .filter(item -> productId.equals(Long.parseLong(item.getSupplierGoodId()))).mapToInt(item -> Integer.parseInt(item.getGoodCount())).sum();
                if (productCount != 0 && (productCount + number) > inventoryVersion) {
                    throw new RuntimeException("vip礼包超过限购次数");
                }
            }
        }
    }

    /**
     * 查询 积分商城列表
     */
    @Override
    public AppletBdmUserIntegralGoodVo integralGoodList() {
        Long userId = SecurityUtils.getUserId();
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, userId).one();
        AppletBdmUserIntegralGoodVo appletBdmUserIntegralGoodVo = BeanUtil.copyProperties(bdmUser, AppletBdmUserIntegralGoodVo.class);
        appletBdmUserIntegralGoodVo.setAppletBdmIntegralGoodVos(bdmGoodMapper.integralGoodList());
        return appletBdmUserIntegralGoodVo;
    }

    /**
     * 新增积分商品
     */
    @Override
    public boolean integralGood(IntegralGoodDto integralGoodDto) {
        BdmGood bdmGood = BeanUtil.copyProperties(integralGoodDto, BdmGood.class);
        bdmGood.setPointsRedemption(BdmGoodEnum.DEDUCTION.getType().toString());
        if (StringUtils.isEmpty(integralGoodDto.getPointsUse())) {
            bdmGood.setPointsUse("0");
        }
        if (ObjectUtils.isEmpty(integralGoodDto.getIntegralPrice())) {
            bdmGood.setIntegralPrice(new BigDecimal("0"));
        }
        return this.updateById(bdmGood);
    }

    /**
     * 增减库存   type   BdmGoodEnum.SUB.getType() 减库存    BdmGoodEnum.ADD.getType()  回库存
     */
    @Override
    public void addOrRollBackStock(List<BdmOrderItem> bdmOrderItems, Long type) {
        int cardinalNumber = 1;

        if (ObjectUtils.isNotEmpty(type) && type.equals(BdmGoodEnum.ADD.getType())) {
            cardinalNumber = -1;
        }
        //批量回库存
        //获取sqlSession
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        //获取 库存和积分mapper
        BdmGoodMapper bdmGoodMapper = sqlSession.getMapper(BdmGoodMapper.class);
        try {
            //回库存
            for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
                int i = bdmGoodMapper.reduceInventory(bdmOrderItem.getSupplierGoodId(), String.valueOf(Integer.parseInt(bdmOrderItem.getGoodCount()) * cardinalNumber));//  商品id   本次购买数量
                if (i == 0) {
                    throw new RuntimeException("操作失败请联系管理员");
                }
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public List<ProductReviewsVo> productReviews(Long goodId) {
        return bdmGoodMapper.productReviews(goodId);

    }


    /**
     * 积分商城兑换记录
     */
    @Override
    public List<PointExchangeRecord> pointExchangeRecord(PointExchangeRecordDto pointExchangeRecordDto) {
        return bdmGoodMapper.pointExchangeRecord(pointExchangeRecordDto);
    }

    /**
     * 补货查看商品详情
     */
    @Override
    public CommodityDetailsVo getCommodityDetails(Long goodId) {

        return bdmGoodMapper.getCommodityDetails(goodId, SecurityUtils.getUserId());

    }

    /**
     * 商品导入
     *
     * @param file
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void importProduct(MultipartFile file) {
        try {
            ExcelUtil<BdmImportGoodDto> util = new ExcelUtil<>(BdmImportGoodDto.class);
            List<BdmImportGoodDto> productList = util.importExcel(file.getInputStream());
            if (CollectionUtils.isEmpty(productList)) {
                throw new RuntimeException("商品数据不能为空");
            }
            List<BdmGood> goodList = productList.stream().map(item -> {
                BdmGood bdmGood = new BdmGood();
                BeanUtil.copyProperties(item, bdmGood);
                bdmGood.setIsInitiate(item.getIsInitiate().equals("上架") ? "1" : "2");
                bdmGood.setMallDisplay("1");
                bdmGood.setGoodType("1");
                bdmGood.setGoodId(item.getId());
                if (item.getClassOneName().equals("大礼包")) {
                    bdmGood.setClassOneId(3L);
                }

                if (item.getClassOneName().equals("VIP套盒")) {
                    bdmGood.setClassOneId(4L);
                }

                if (item.getClassOneName().equals("积分商品")) {
                    bdmGood.setClassOneId(7L);
                }

                if (item.getClassOneName().equals("热门复购")) {
                    bdmGood.setClassOneId(2L);
                }
                bdmGood.setCreateTime(new Date());
                return bdmGood;
            }).collect(Collectors.toList());
            this.saveBatch(goodList);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("商品数据导入失败");
        }
    }

    /**
     * 获取商品二维码
     *
     * @param goodId
     * @return
     */
    @Override
    public AjaxResult getGoodQrCode(Long goodId, Long userId) {
        try {
            // 1️⃣ 获取 access_token
            String accessToken = getAccessToken();

            // 2️⃣ 获取商品详情
            AppletBdmGoodVo goodVo = goodVo(goodId);

            // 3️⃣ 构建二维码请求参数
            String qrUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            URL url = new URL(qrUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");

            JSONObject param = new JSONObject();
            param.put("scene", "id=" + goodId + "&userId=" + userId);
            param.put("page", "subPages/details/goodDetail");
            param.put("width", 430);
            param.put("is_hyaline", true);
            param.put("check_path", false);
            param.put("env_version", "release");// 线上 release  体验 trial  开发 develop

            // 写入请求体
            try (OutputStream os = connection.getOutputStream();
                 OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8")) {
                osw.write(param.toJSONString());
                osw.flush();
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                try (InputStream inputStream = connection.getInputStream();
                     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, bytesRead);
                    }
                    byte[] data = byteArrayOutputStream.toByteArray();

                    // 4️⃣ 保存到本地文件
                    String fileName = "goods-" + goodId + "-qr.png";
                    String filePath = RuoYiConfig.getUploadPath() + "/" + fileName;

                    File file = new File(filePath);
                    File parentDir = file.getParentFile();
                    if (!parentDir.exists()) {
                        parentDir.mkdirs();
                    }

                    try (FileOutputStream fos = new FileOutputStream(file)) {
                        fos.write(data);
                    }

                    // 5️⃣ 返回前端访问路径（注意：若依默认 /profile 映射到 RuoYiConfig.uploadPath）
                    String visitPath = "/profile/upload/" + fileName;
                    return AjaxResult.success(visitPath);
                }
            } else {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        errorResponse.append(line);
                    }
                    return AjaxResult.error("请求失败: " + responseCode + "，错误信息: " + errorResponse);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("生成二维码失败: " + e.getMessage());
        }
    }

    @Override
    public AjaxResult getCostPrice(BdmCloudInventoryItemVoList bdmCloudInventoryItemVoList) {
        BigDecimal costPrice = BigDecimal.ZERO;
        List<BamCloudInventoryVo> list = bdmCloudInventoryItemVoList.getList();
        for (BamCloudInventoryVo id : list) {
            CommodityDetailsVo commodityDetails = getCommodityDetails(id.getGoodId());
            Double replenishmentPrice = commodityDetails.getReplenishmentPrice();
            replenishmentPrice = replenishmentPrice * id.getCount();
            costPrice = costPrice.add(BigDecimal.valueOf(replenishmentPrice));
        }

        BdmShippingCost bdmShippingCost = new BdmShippingCost();
        bdmShippingCost.setType(2);
        List<BdmShippingCost> shippingCosts = bdmShippingCostService.selectBdmShippingCostList(bdmShippingCost);

        if (shippingCosts.isEmpty()) {
            // 没有运费配置
            return AjaxResult.success(Map.of("price", BigDecimal.ZERO, "costPrice", costPrice));
        }

        // 找出最小 startPrice 和最大 endPrice
        BdmShippingCost minShipping = shippingCosts.stream()
                .min(Comparator.comparing(BdmShippingCost::getStartPrice)).get();
        BdmShippingCost maxShipping = shippingCosts.stream()
                .max(Comparator.comparing(BdmShippingCost::getEndPrice)).get();

        // 小于最小区间 → 取最小运费
        if (costPrice.compareTo(minShipping.getStartPrice()) < 0) {
            return AjaxResult.success(Map.of("price", minShipping.getPrice(), "costPrice", costPrice));
        }

        // 落在某个区间 → 取该区间运费
        for (BdmShippingCost sc : shippingCosts) {
            if (costPrice.compareTo(sc.getStartPrice()) >= 0 && costPrice.compareTo(sc.getEndPrice()) <= 0) {
                return AjaxResult.success(Map.of("price", sc.getPrice(), "costPrice", costPrice));
            }
        }

        // 大于最大区间 或者 落在空白区间 → 统一取最大运费
        return AjaxResult.success(Map.of("price", maxShipping.getPrice(), "costPrice", costPrice));
    }



    private String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token" +
                "?grant_type=client_credential" +
                "&appid=" + WxConfig.APP_ID +
                "&secret=" + WxConfig.secret;

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String responseBody = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(responseBody);

        return jsonObject.getString("access_token");
    }


}
